package cn.melonlib.cores.commons.comp.web.resolvers;

import cn.melonlib.cores.commons.comp.web.ctrl.BasicController;
import cn.melonlib.cores.jpa.model.bean.collections.JsonMap;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.util.Arrays;
import java.util.stream.Collectors;

@Component
public class ApiExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        response.setContentType(BasicController.APPLICATION_JSON_UTF8_VALUE);
        response.setCharacterEncoding("utf-8");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        try(Writer out=response.getWriter()){
         out.append(JsonMap.createMap().append("status",500).append("errorMessage", Arrays.stream(ex.getMessage().split("\\$#\\$")).collect(Collectors.toList())).jsonString());
        }catch(Exception e){
        }
        return null;
    }
}
